package org.Lin.server;

import java.util.List;
import java.util.concurrent.*;

public class pollerServer implements Runnable {

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void startPolling() {
        scheduler.scheduleAtFixedRate(new pollerServer(), 0, 5, TimeUnit.SECONDS);
    }

    @Override
    public void run() {
        List<questionModel> pending = dbUtil.getPendingQuestions();
        ExecutorService executor = Executors.newFixedThreadPool(10);

        for (questionModel q : pending) {
            executor.submit(() -> {
                String currentModel = q.getModelUsed();
                if (currentModel != null && !currentModel.isEmpty()) {
                    System.out.println("问题 ID: " + q.getId() + " 已有模型记录，跳过处理");
                    return;
                }

                apiService.LLMResponse response;
                response = apiService.callAvailableModel(q.getQuestion(), currentModel, q.getId(), q.getAnswer());

                dbUtil.updateAnswer(q.getId(), response.content, response.model);
            });
        }

        executor.shutdown();
    }
}